package org.example.software.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.example.software.entity.Admin;
import org.example.software.exception.MyException;
import org.example.software.mapper.AdminMapper;
import org.example.software.service.AdminService;
import org.example.software.utils.JwtUtil;
import org.mybatis.logging.Logger;
import org.mybatis.logging.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

@Service
public class AdminServiceImpl implements AdminService {

    @Autowired
    private AdminMapper adminMapper;

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    private static final Logger logger = LoggerFactory.getLogger(AdminServiceImpl.class);

    // 管理员注册
    @Override
    public boolean register(Admin admin) {
        QueryWrapper<Admin> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", admin.getId());

        // 检查用户是否已存在
        if (adminMapper.selectCount(queryWrapper) > 0) {
            MyException.throwError("该用户已存在", 409);
        }
        // 检查用户账号是否位空
        if (admin.getId() == null || admin.getId().isEmpty()) {
            MyException.throwError("账号不能为空", 400);
        }

        // 检查密码长度
        if (admin.getPassword() == null || admin.getPassword().length() < 6 ||admin.getPassword().length() > 13) {
            MyException.throwError("密码长度必须大于5位且小于13位", 400);
        }

        // 加密密码并保存
        admin.setPassword(passwordEncoder.encode(admin.getPassword()));
        boolean success = adminMapper.insert(admin) > 0;
        return success;
    }

    //管理员登录
    @Override
    public String login(Admin admin) {
        QueryWrapper<Admin> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", admin.getId());
        Admin storedAdmin = adminMapper.selectOne(queryWrapper);

        if (storedAdmin == null || !passwordEncoder.matches(admin.getPassword(), storedAdmin.getPassword())) {
            MyException.throwError("登录失败，用户不存在或者密码错误", 401);
        }

        // 使用 JWT 生成 Token
        return JwtUtil.generateToken(admin.getId(),true);
    }

}
